package cn.angis.db.controller;

import cn.angis.common.model.PageModel;
import cn.angis.common.model.PageResult;
import cn.angis.common.model.R;
import cn.angis.common.util.SystemType;
import cn.angis.db.service.BaseService;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.UploadedFile;
import org.noear.solon.data.annotation.Tran;
import org.noear.solon.validation.annotation.Valid;
import org.sagacity.sqltoy.model.Page;

import java.io.File;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.util.*;

/**
 * 包名称：cn.angis.db.model
 * 类名称：BaseService
 * 类描述：公共controller
 * 创建人：@author angis.cn
 * 创建日期： 2022/11/28 11:35
 */
@Valid
public abstract class BaseController<Service extends BaseService, T extends Serializable> extends RBaseController {

    @Inject
    protected Service baseService;

    /**
     * 转换page
     *
     * @param pageModel model分页数据
     * @param entity  实体数据
     * @return
     */
    protected PageResult<T> pageListByEntity(T entity, PageModel pageModel, String sqlId) {
        PageResult<T> pageResult = new PageResult<>();
        Page<T> request = new Page<T>(pageModel.getSize(), pageModel.getCurrent());
        Page<T> result = baseService.page(entity, request, sqlId);
        pageResult.setCurrent(pageModel.getCurrent());
        pageResult.setPages(result.getTotalPage());
        pageResult.setSize(pageModel.getSize());
        pageResult.setTotal(result.getRecordCount());
        pageResult.setRecords(result.getRows());
        return pageResult;
    }

    protected <DTO> PageResult<DTO> toPageDTO(PageResult<T> page, List<DTO> list) {
        PageResult<DTO> pageResult = new PageResult<>();
        pageResult.setCurrent(page.getCurrent());
        pageResult.setPages(page.getPages());
        pageResult.setSize(page.getSize());
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(list);
        return pageResult;
    }

    /**
     * 查询全部
     *
     * @return
     */
    public List<T> all(T entity) {
        return baseService.all(entity);
    }


    /**
     * 根据对象id，查询详细信息
     *
     * @param entity
     * @return
     */
    public T getById(T entity) {
        return (T) baseService.getById(entity);
    }

    /**
     * 添加
     *
     * @param entity
     * @return
     */
    public R<Boolean> save(T entity) {
        baseService.save(entity);
        return success(true);
    }

    /**
     * 批量添加
     *
     * @param list
     * @return
     */
    @Tran
    public R<Boolean> saveBatch(List<T> list) {
        baseService.saveBatch(list);
        return success(true);
    }

    /**
     * 修改
     *
     * @param entity
     * @return
     */
    public R<Boolean> update(T entity) {
        return success(baseService.update(entity)>=1);
    }

    /**
     * 批量修改
     *
     * @param list
     * @return
     */
    @Tran
    public R<Boolean> updateBatch(List<T> list) {
        return success(baseService.updateBatch(list)>0);
    }

    /**
     * 删除
     *
     * @param entity
     * @return
     */
    public R<Boolean> delete(T entity) {
        return success(baseService.delete(entity)>=1);
    }

    /**
     * 根据idList删除（对应的泛型是基本数据类型）
     *
     * @param idList
     * @return
     */
    @Tran
    public R<Boolean> deleteBatch(Class<?> cls, List<String> idList) {
        return success(baseService.deleteBatch(cls, idList)>0);
    }

    /**
     * 根据id集合查找实体列表
     * @param cls
     * @param ids
     * @return: R<List<Entity>>
     * @throws: 
     * @Date: 2023/1/7     
     */
    public List<T> listByIds(Class<?> cls, List<String> ids) {
        return baseService.listByIds(cls, ids);
    }

    protected R<Object> upload(UploadedFile file, String userPath) {
        String fileSavePath = System.getProperty("user.dir") + File.separator + "upload";
        Set<PosixFilePermission> perms = null;
        if (SystemType.isLinux()) {
            perms = new HashSet<PosixFilePermission>();
            perms.add(PosixFilePermission.OWNER_READ);//设置所有者的读取权限
            perms.add(PosixFilePermission.OWNER_WRITE);//设置所有者的写权限
            perms.add(PosixFilePermission.OWNER_EXECUTE);//设置所有者的执行权限
            perms.add(PosixFilePermission.GROUP_READ);//设置组的读取权限
            perms.add(PosixFilePermission.GROUP_EXECUTE);//设置组的读取权限
            perms.add(PosixFilePermission.OTHERS_READ);//设置其他的读取权限
            perms.add(PosixFilePermission.OTHERS_EXECUTE);//设置其他的读取权限
        }

        Map<String, Object> result = new HashMap<>();
        String dirDate = userPath + File.separator + DatePattern.SIMPLE_MONTH_FORMAT.format(new Date());
        File dir = new File(fileSavePath + File.separator + dirDate);
        if (!dir.exists())// 目录不存在则创建
            dir.mkdirs();
        String fileNames = "";
        try {
            if (SystemType.isLinux()) {
                Path path = Paths.get(dir.getAbsolutePath());
                Files.setPosixFilePermissions(path, perms);
            }
            String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase();

            String fileNameNew = dirDate + File.separator + DateUtil.current() + "." + suffix;
            File tagetFile = new File(fileSavePath + File.separator + fileNameNew);
            fileNames = fileNameNew;
            tagetFile.createNewFile();
            // 保存文件到硬盘
            if ("jpgpnggifbmpjpeg".indexOf(suffix)>-1) {
                Thumbnails.of(file.getContent())
                        .scale(1f)
                        .outputQuality(0.75f).toFile(tagetFile);

            } else {
                file.transferTo(tagetFile);
            }
            Path filepath = Paths.get(tagetFile.getAbsolutePath());
            if (SystemType.isLinux()) {
                Files.setPosixFilePermissions(filepath, perms);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return success(fileNames);
    }


//    protected <Entity> DownloadedFile downloadExcel(Context ctx, List<Entity> data, Class<Entity> cls, String fileName, String titleName) {
//        String sheetName = fileName;
//        try {
//            EasyExcel.write(ctx.outputStream(), cls).sheet("模板").doWrite(data);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return new DownloadedFile("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", stream, "logo-new.jpg");
//    }

}
